package com.vlh.battleship.server.integration.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

import com.vlh.battleship.server.config.DataSourceConfiguration;
import com.vlh.battleship.server.integration.dto.Player;
import com.vlh.battleship.server.integration.dto.board.EmptyTile;
import com.vlh.battleship.server.integration.dto.board.Tile;
import com.vlh.battleship.server.integration.dto.game.Game;
import com.vlh.battleship.server.integration.dto.ship.ShipPiece;

public class GameDao {
	
	private DataSource ds;
	
	public GameDao() {
		ApplicationContext ctx = new AnnotationConfigApplicationContext(DataSourceConfiguration.class);
		ds = ctx.getBean(DataSource.class);
	}
	public void setDateSource(DataSource ds) {
		this.ds = ds;
	}

	public void saveGame(Game g) {

	}
	
	public void updateTile(Tile t, Game g) {
		NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(ds);
		int type = 0;
		if (t.getClass().isAssignableFrom(EmptyTile.class)) {
			type = 0;
		} else if (t.getClass().isAssignableFrom(ShipPiece.class)) {
			type = 1;
		}
		Map<String, Integer> params = new HashMap<String, Integer>();
		params.put("type", type);
		params.put("status", t.getStatus());
		params.put("picture_id", t.getPictureId());
		params.put("game_id", g.getId());
		params.put("x", t.getXPos());
		params.put("y", t.getYPos());
		jdbcTemplate.update(Sql.updateTile, params);
	}

	public List<Game> getGames() {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
		return jdbcTemplate.query(Sql.getGames, new GameRowMapper());
	}
	
	public List<Tile> getTiles(Game g) {
		NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(ds);
		SqlParameterSource params = new MapSqlParameterSource("game_id", g.getId());
		return jdbcTemplate.query(Sql.getTilesForGame, params, new TileRowMapper());
	}

	public List<Player> getPlayers() {
		// TODO Auto-generated method stub
		return null;
	}

}
